package com.software.loginregister.fragment;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.software.loginregister.MainActivity;
import com.software.loginregister.R;
import com.software.loginregister.adapter.ChatAdapter;
import com.software.loginregister.adapter.ConversationHistoryAdapter;

import com.software.loginregister.entity.ChatHistoryMessage;
import com.software.loginregister.entity.ChatMessage;
import com.google.android.material.button.MaterialButton;

import com.software.loginregister.entity.ConversationHistory;
import com.software.loginregister.entity.Result;
import com.software.loginregister.util.RetrofitClient;
import com.software.loginregister.util.SharedPreferencesUtil;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import io.noties.markwon.Markwon;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * A simple {@link Fragment} subclass.
 */
public class AiFragment extends Fragment {

    private View rootView;
    private TextView tvInputHint;  // 替换原有的etInput
    private View llInputArea;      // 输入区域容器
    private MaterialButton tvHistory;

    private RecyclerView rvChat;
    private ChatAdapter chatAdapter;
    private String currentConversationId;

    private BottomSheetDialog inputDialog;  // 添加底部弹出对话框
    private EditText dialogInput;           // 对话框中的输入框
    private ImageButton btnDialogSend;      // 对话框中的发送按钮
    private TextView tvNewMessage;
    private View dialogView;
    private Markwon markwon;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_ai, container, false);
        initViews();
        setupRecyclerView();
        currentConversationId = SharedPreferencesUtil.getConversationId(getContext());
        Log.d("AiFragment", "恢复的会话ID: " + currentConversationId); // 添加日志
        markwon = Markwon.create(requireContext());
        setupListeners();
        addAiMessage("试试发送一些问题给我，比如制定一个健身计划，我想要在一个月内减肥10斤");

        return rootView;
    }

    private void initViews() {
        tvInputHint = rootView.findViewById(R.id.tv_input_hint);
        llInputArea = rootView.findViewById(R.id.ll_input_area);
        tvHistory = rootView.findViewById(R.id.tv_ai_history);
        tvNewMessage = rootView.findViewById(R.id.tv_new_message);
        rvChat = rootView.findViewById(R.id.rv_chat);

        // 设置焦点变化监听器
        setupInputDialog();
    }

    private void setupInputDialog() {
        inputDialog = new BottomSheetDialog(requireContext());
        dialogView = getLayoutInflater().inflate(R.layout.dialog_input, null);
        dialogInput = dialogView.findViewById(R.id.et_input);
        btnDialogSend = dialogView.findViewById(R.id.btn_send);

        // 设置点击事件
        btnDialogSend.setOnClickListener(v -> {
            String message = dialogInput.getText().toString().trim();
            if (!TextUtils.isEmpty(message)) {
                addUserMessage(message);
                dialogInput.setText("");
                simulateAiResponse(message);
                inputDialog.dismiss();
            }
        });

        inputDialog.setContentView(dialogView);

        // 修改焦点管理
        inputDialog.setOnShowListener(dialog -> {
            // 延迟设置焦点，避免冲突
            dialogInput.post(() -> {
                dialogInput.requestFocus();
                InputMethodManager imm = (InputMethodManager) requireContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(dialogInput, InputMethodManager.SHOW_IMPLICIT);
            });
        });

        // 确保关闭时清理焦点和键盘
        inputDialog.setOnDismissListener(dialog -> {
            dialogInput.clearFocus();
            InputMethodManager imm = (InputMethodManager) requireContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(dialogInput.getWindowToken(), 0);
        });
    }
    //输出验证
    private boolean isValidInput(String input) {
        return input != null && !input.trim().isEmpty() && input.length() <= 1000; // 设置合理的长度限制
    }

    private void setupRecyclerView() {
        chatAdapter = new ChatAdapter(getContext());
        rvChat.setLayoutManager(new LinearLayoutManager(getContext()));
        rvChat.setAdapter(chatAdapter);
    }

    private void setupListeners() {
        // 设置输入区域点击事件
        llInputArea.setOnClickListener(v -> showInputDialog());
        tvInputHint.setOnClickListener(v -> showInputDialog());

        // 历史记录按钮点击事件
        tvHistory.setOnClickListener(v -> showHistoryDialog());

        // 新会话按钮点击事件
        tvNewMessage.setOnClickListener(v -> {
            // 直接清空当前会话ID
            currentConversationId = null;
            SharedPreferencesUtil.saveConversationId(getContext(), null);

            // 清空消息列表
            chatAdapter.getMessages().clear();
            chatAdapter.notifyDataSetChanged();

            // 清空输入框
            dialogInput.setText("");

            // 添加默认欢迎消息
            addAiMessage("试试发送一些问题给我，比如制定一个健身计划，我想要在一个月内减肥10斤");

            Toast.makeText(getContext(), "已创建新会话", Toast.LENGTH_SHORT).show();
            Log.d("AiFragment", "已清除会话ID，准备开始新会话");
        });
    }

    private void showInputDialog() {
        if (inputDialog != null && !inputDialog.isShowing()) {
            inputDialog.show();
        }
    }

    private void showHistoryDialog() {
        Dialog dialog = new Dialog(requireContext());
        dialog.setContentView(R.layout.dialog_conversation_history);

        // 设置对话框宽度为屏幕宽度的90%
        Window window = dialog.getWindow();
        if (window != null) {
            WindowManager.LayoutParams params = window.getAttributes();
            params.width = (int) (getResources().getDisplayMetrics().widthPixels * 0.9);
            window.setAttributes(params);
            window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        }

        RecyclerView recyclerView = dialog.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(requireContext()));
        recyclerView.addItemDecoration(new DividerItemDecoration(requireContext(), DividerItemDecoration.VERTICAL));

        // 添加条目动画
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        ConversationHistoryAdapter adapter = new ConversationHistoryAdapter(getContext());
        recyclerView.setAdapter(adapter);

        // 设置点击事件
        adapter.setOnItemClickListener(history -> {
            dialog.dismiss();
            currentConversationId = history.getId();
            SharedPreferencesUtil.saveConversationId(getContext(), currentConversationId);
            // 加载会话消息
            loadConversationMessages(currentConversationId);
        });

        // 加载历史记录
        loadHistories(adapter, dialog.findViewById(R.id.progressBar),
                dialog.findViewById(R.id.tvEmpty), recyclerView);

        dialog.show();

        adapter.setOnItemLongClickListener(history -> {
            new AlertDialog.Builder(requireContext())
                    .setTitle("删除确认")
                    .setMessage("确定要删除这条会话记录吗？")
                    .setPositiveButton("确定", (dialog1, which) -> {
                        deleteConversation(history, adapter);
                    })
                    .setNegativeButton("取消", null)
                    .show();
        });
    }

    private void deleteConversation(ConversationHistory history, ConversationHistoryAdapter adapter) {
        String appId = "app2";
        Long userId = SharedPreferencesUtil.getUserId(getContext());
        if (userId == null) {
            showError("请先登录");
            return;
        }

        showLoading();

        // 打印详细的请求参数
        Log.d("AiFragment", String.format("删除会话参数: userId=%s, appId=%s, conversationId=%s",
                userId, appId, history.getId()));

        RetrofitClient.getInstance()
                .getChatApi()
                .deleteConversation(
                        String.valueOf(userId),  // 先传 userId
                        appId,                   // 然后是 appId
                        history.getId()          // 最后是 conversationId
                )
                .enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        hideLoading();
                        // 打印完整请求URL和响应码
                        Log.d("AiFragment", "请求URL: " + call.request().url());
                        Log.d("AiFragment", "响应码: " + response.code());

                        if (response.isSuccessful()) {
                            Toast.makeText(requireContext(), "删除成功", Toast.LENGTH_SHORT).show();
                            // 如果删除的是当前会话，清除当前会话ID
                            if (history.getId().equals(currentConversationId)) {
                                currentConversationId = null;
                                SharedPreferencesUtil.saveConversationId(getContext(), null);
                                // 清空当前消息列表
                                chatAdapter.getMessages().clear();
                                chatAdapter.notifyDataSetChanged();
                            }
                            // 重新加载会话列表，传入 adapter 但其他参数为 null
                            loadHistories(adapter, null, null, null);
                        } else {
                            try {
                                String errorBody = response.errorBody() != null ?
                                        response.errorBody().string() : "未知错误";
                                Log.e("AiFragment", "删除失败: " + errorBody);
                                Log.e("AiFragment", "HTTP状态码: " + response.code());
                                // 打印请求头信息
                                Log.e("AiFragment", "请求头: " + call.request().headers());

                                Toast.makeText(requireContext(),
                                        "删除失败: " + response.code() + " " + errorBody,
                                        Toast.LENGTH_SHORT).show();
                            } catch (IOException e) {
                                Toast.makeText(requireContext(),
                                        "删除失败: " + response.code(),
                                        Toast.LENGTH_SHORT).show();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        hideLoading();
                        Log.e("AiFragment", "删除请求失败: " + t.getMessage());
                        Log.e("AiFragment", "失败详情", t);  // 打印完整堆栈
                        Toast.makeText(requireContext(),
                                "网络错误: " + t.getMessage(),
                                Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void loadHistories(ConversationHistoryAdapter adapter, ProgressBar progressBar, TextView tvEmpty, RecyclerView recyclerView) {
        // 检查参数是否为 null
        if (progressBar != null) {
            progressBar.setVisibility(View.VISIBLE);
        }
        if (recyclerView != null) {
            recyclerView.setVisibility(View.GONE);
        }
        if (tvEmpty != null) {
            tvEmpty.setVisibility(View.GONE);
        }

        Long userId = SharedPreferencesUtil.getUserId(getContext());
        if (userId == null) {
            showError("请先登录");
            return;
        }

        RetrofitClient.getInstance()
                .getChatApi()
                .getConversationHistory(
                        String.valueOf(userId),
                        "app2",
                        "",
                        20
                )
                .enqueue(new Callback<List<ConversationHistory>>() {
                    @Override
                    public void onResponse(Call<List<ConversationHistory>> call,
                                           Response<List<ConversationHistory>> response) {
                        // 检查参数是否为 null
                        if (progressBar != null) {
                            progressBar.setVisibility(View.GONE);
                        }

                        if (response.isSuccessful() && response.body() != null) {
                            List<ConversationHistory> histories = response.body();
                            if (histories.isEmpty()) {
                                if (tvEmpty != null) {
                                    tvEmpty.setVisibility(View.VISIBLE);
                                }
                            } else {
                                if (recyclerView != null) {
                                    recyclerView.setVisibility(View.VISIBLE);
                                }
                                adapter.setHistories(histories);
                            }
                        } else {
                            showError("获取历史记录失败");
                        }
                    }

                    @Override
                    public void onFailure(Call<List<ConversationHistory>> call, Throwable t) {
                        // 检查参数是否为 null
                        if (progressBar != null) {
                            progressBar.setVisibility(View.GONE);
                        }
                        showError("网络错误: " + t.getMessage());
                    }
                });
    }

    private void addUserMessage(String message) {
        // 从 SharedPreferences 获取用户头像 URL
        String userAvatarUrl = SharedPreferencesUtil.getUserAvatar(getContext());

        // 创建消息对象并添加到适配器
        ChatMessage chatMessage = new ChatMessage(message, true, userAvatarUrl);
        chatAdapter.addMessage(chatMessage);
        scrollToBottom();
    }

    private void addAiMessage(String message) {
        String markdownMessage = formatToMarkdown(message);
        // AI 消息使用 null 作为头像 URL，将使用默认的 AI 头像资源
        ChatMessage chatMessage = new ChatMessage(markdownMessage, false, null);
        chatAdapter.addMessage(chatMessage);
        scrollToBottom();
    }

    private String formatToMarkdown(String message) {
        // 检查消息是否包含标题、列表等特定格式
        if (message.contains("材料清单:") || message.contains("制作步骤:")) {
            StringBuilder markdown = new StringBuilder();
            String[] lines = message.split("\n");

            for (String line : lines) {
                line = line.trim();
                // 处理标题
                if (line.endsWith(":")) {
                    markdown.append("### ").append(line).append("\n\n");
                }
                // 处理列表项
                else if (line.startsWith("•")) {
                    markdown.append("- ").append(line.substring(1).trim()).append("\n");
                }
                // 处理数字列表
                else if (line.matches("^\\d+\\..*")) {
                    markdown.append(line).append("\n");
                }
                // 处理子项
                else if (line.startsWith("-")) {
                    markdown.append("    ").append(line).append("\n");
                }
                // 普通文本
                else if (!line.isEmpty()) {
                    markdown.append(line).append("\n\n");
                }
            }
            return markdown.toString();
        }
        return message;
    }

    private void scrollToBottom() {
        rvChat.post(() -> rvChat.smoothScrollToPosition(chatAdapter.getItemCount() - 1));
    }

    private void simulateAiResponse(String userMessage) {
        addAiMessage("正在思考...");

        Map<String, String> requestBody = new HashMap<>();
        requestBody.put("message", userMessage);
        requestBody.put("userId", String.valueOf(SharedPreferencesUtil.getUserId(getContext())));
        requestBody.put("newConversation", String.valueOf(currentConversationId == null));

        // 添加时间戳作为会话标识符的一部分，确保每次新会话都是唯一的
        if (currentConversationId == null) {
            requestBody.put("timestamp", String.valueOf(System.currentTimeMillis()));
            Log.d("AiFragment", "创建全新会话");
        } else {
            requestBody.put("conversationId", currentConversationId);
            Log.d("AiFragment", "继续现有会话: " + currentConversationId);
        }

        RetrofitClient.getInstance()
                .getChatApi()
                .sendMessage(requestBody)
                .enqueue(new retrofit2.Callback<ResponseBody>() {
                    @Override
                    public void onResponse(retrofit2.Call<ResponseBody> call,
                                           retrofit2.Response<ResponseBody> response) {
                        if (getActivity() == null) {
                            return;
                        }

                        if (response.isSuccessful() && response.body() != null) {
                            try {
                                // 从响应头中获取会话ID
                                String newConversationId = response.headers().get("conversation_id");
                                if (newConversationId == null) {
                                    newConversationId = response.headers().get("conversationId");
                                }

                                // 如果找到了会话ID，保存它
                                // 在获取新的 conversationId 时，检查是否是新会话
                                if (currentConversationId == null && newConversationId != null) {
                                    currentConversationId = newConversationId;
                                    SharedPreferencesUtil.saveConversationId(getContext(), newConversationId);
                                    Log.d("AiFragment", "获得新会话ID: " + newConversationId);
                                }

                                // 获取响应内容
                                String responseData = response.body().string();
                                Log.d("AiFragment", "Raw Response: " + responseData);

                                if (getActivity() != null) {
                                    getActivity().runOnUiThread(() -> {
                                        chatAdapter.removeLastMessage();
                                    });
                                }

                                // 处理响应文本
                                String finalResponse = responseData;
                                if (responseData.startsWith("\"") && responseData.endsWith("\"")) {
                                    finalResponse = responseData.substring(1, responseData.length() - 1);
                                }
                                finalResponse = finalResponse.replace("\\n", "\n")
                                        .replace("\\\"", "\"")
                                        .replace("\\\\", "\\");

                                // 显示消息
                                final String displayMessage = finalResponse;
                                if (getActivity() != null) {
                                    getActivity().runOnUiThread(() -> {
                                        addAiMessage(displayMessage);
                                        scrollToBottom();
                                    });
                                }

                            } catch (IOException e) {
                                Log.e("AiFragment", "IO错误: " + e.getMessage());
                                showError("读取响应失败：" + e.getMessage());
                            }
                        } else {
                            try {
                                String errorBody = response.errorBody() != null ?
                                        response.errorBody().string() : "未知错误";
                                Log.e("AiFragment", "请求失败: " + errorBody);
                                showError("请求失败: " + response.code() + " " + errorBody);
                            } catch (IOException e) {
                                showError("请求失败: " + response.code());
                            }
                        }
                    }

                    @Override
                    public void onFailure(retrofit2.Call<ResponseBody> call, Throwable t) {
                        Log.e("AiFragment", "网络错误: " + t.getMessage());
                        showError("网络错误：" + t.getMessage());
                    }
                });
    }

    private void showError(String errorMessage) {
        if (getActivity() != null) {
            getActivity().runOnUiThread(() -> {
                chatAdapter.removeLastMessage();
                addAiMessage("抱歉，出现了一些问题：" + errorMessage);
            });
        }
    }

    // 添加加载对话框
    private ProgressDialog progressDialog;

    private void showLoading() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(getContext());
            progressDialog.setMessage("加载中...");
            progressDialog.setCancelable(false);
        }
        progressDialog.show();
    }

    private void hideLoading() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    // 加载会话消息
    private void loadConversationMessages(String conversationId) {
        if (conversationId == null || getContext() == null) return;

        Long userId = SharedPreferencesUtil.getUserId(getContext());
        if (userId == null) {
            showError("请先登录");
            return;
        }

        showLoading();

        // 添加请求参数日志
        Log.d("AiFragment", String.format("加载会话消息: userId=%s, appId=app2, conversationId=%s",
                userId, conversationId));

        // 清空当前消息列表
        chatAdapter.getMessages().clear();
        chatAdapter.notifyDataSetChanged();

        RetrofitClient.getInstance()
                .getChatApi()
                .getMessages(
                        String.valueOf(userId),
                        "app2",
                        conversationId,
                        50
                )
                .enqueue(new Callback<List<ChatHistoryMessage>>() {
                    @Override
                    public void onResponse(Call<List<ChatHistoryMessage>> call,
                                           Response<List<ChatHistoryMessage>> response) {
                        hideLoading();

                        // 添加响应日志
                        Log.d("AiFragment", "收到响应: " + response.code());
                        if (!response.isSuccessful()) {
                            try {
                                Log.e("AiFragment", "错误响应: " + response.errorBody().string());
                            } catch (Exception e) {
                                Log.e("AiFragment", "读取错误响应失败", e);
                            }
                        }

                        if (response.isSuccessful() && response.body() != null) {
                            List<ChatHistoryMessage> messages = response.body();
                            String userAvatarUrl = SharedPreferencesUtil.getUserAvatar(getContext());

                            for (ChatHistoryMessage historyMessage : messages) {
                                // 添加用户消息
                                if (historyMessage.getQuery() != null && !historyMessage.getQuery().isEmpty()) {
                                    chatAdapter.addMessage(new ChatMessage(
                                            historyMessage.getQuery(),
                                            true,
                                            userAvatarUrl
                                    ));
                                }
                                // 添加AI回答
                                if (historyMessage.getAnswer() != null && !historyMessage.getAnswer().isEmpty()) {
                                    chatAdapter.addMessage(new ChatMessage(
                                            historyMessage.getAnswer(),
                                            false,
                                            null  // AI 消息使用默认头像
                                    ));
                                }
                            }
                            scrollToBottom();
                        } else {
                            showError("加载聊天记录失败");
                        }
                    }

                    @Override
                    public void onFailure(Call<List<ChatHistoryMessage>> call, Throwable t) {
                        hideLoading();
                        String errorMsg = "网络错误：" + t.getMessage();
                        showError(errorMsg);
                        Log.e("AiFragment", errorMsg, t);
                    }
                });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        hideLoading();
        if (currentConversationId != null) {
            SharedPreferencesUtil.saveConversationId(getContext(), currentConversationId);
        }
    }
}
